package com.example.wblog.controller.admin;

import com.example.wblog.service.AdminService;
import com.example.wblog.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping({"/admin/reglogin"})
public class RegLoginController {

    @Autowired
    AdminService adminService;

    @RequestMapping({"", "/", "/index"})
    public String index() {
        return "/admin/login";
    }

    @RequestMapping(value = {"/login"}, method = RequestMethod.POST)
    public String login(HttpServletResponse res,
                        @RequestParam("name") String name,
                        @RequestParam("password") String password) {
        Map<String, String> map = adminService.login(name, password);
        if (map.containsKey("ticket")) {
            CookieUtil.setCookie("ticket", map.get("ticket"), res);
            return "redirect:/";
        }
        return "redirect:/admin/reglogin";
    }

    @RequestMapping(value = {"/logout"}, method = RequestMethod.GET)
    public String login(HttpServletRequest request,
                        HttpServletResponse response,
                        @CookieValue("ticket") String ticket) {
        adminService.logout(request, response, ticket);
        return "redirect:/";
    }

}
